package com.doubao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doubao.entity.ChatMessage;
import com.doubao.entity.vo.ChatMessageVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {

    @Select({
        "SELECT m.*, ",
        "CASE WHEN m.role = 'assistant' THEN d.name ELSE u.username END as sender_name,",
        "CASE WHEN m.role = 'assistant' THEN d.icon ELSE u.avatar END as sender_avatar",
        "FROM chat_message m",
        "LEFT JOIN smart_device d ON d.id = m.device_id",
        "LEFT JOIN user u ON u.id = m.user_id",
        "WHERE m.user_id = #{userId}",
        "AND m.device_id = #{deviceId}",
        "AND m.status = 1",
        "ORDER BY m.id DESC"
    })
    IPage<ChatMessageVO> selectMessagePage(Page<?> page,
                                         @Param("userId") Long userId,
                                         @Param("deviceId") Long deviceId);

    @Select({
        "SELECT COUNT(*)",
        "FROM chat_message",
        "WHERE user_id = #{userId}",
        "AND device_id = #{deviceId}",
        "AND status = 1"
    })
    int countUserDeviceMessages(@Param("userId") Long userId,
                              @Param("deviceId") Long deviceId);
}